package cn.ghx.xboot.order.appointment;

import cn.ghx.xboot.common.BaseContext;
import cn.ghx.xboot.item.ItemService;
import cn.ghx.xboot.order.dto.OrderStatusDto;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ghx.xboot.mapper.OrderAppointmentMapper;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

/**
 * @author ghx
 * @description 针对表【t_order_appointment(预约单)】的数据库操作Service实现
 * @createDate 2024-04-22 14:16:04
 */
@Service
public class OrderAppointmentService extends ServiceImpl<OrderAppointmentMapper, OrderAppointment> {

    private final ItemService itemService;

    @Lazy
    public OrderAppointmentService(ItemService itemService) {
        this.itemService = itemService;
    }

    public OrderAppointment findById(String id) {
        return wrapExtra(getById(id));
    }

    private OrderAppointment wrapExtra(OrderAppointment item) {
        item.setItem(itemService.detail(item.getItemId()));
        return item;
    }

    public Boolean deleteById(String id) {
        return removeById(id);
    }

    public Boolean saveItem(OrderAppointment item) {
        return saveOrUpdate(item);
    }

    public Page<OrderAppointment> query(String keyword, String openid, String phone,
                                        Integer status,
                                        Integer page, Integer size) {
        LambdaQueryChainWrapper<OrderAppointment> qw = lambdaQuery();
        // 参数
        if (StringUtils.hasText(keyword)) {
            qw.and(w -> {
                w.like(OrderAppointment::getName, keyword).or()
                        .like(OrderAppointment::getRemark, keyword);
            });
        }

        if (StringUtils.hasText(openid)) {
            qw.eq(OrderAppointment::getOpenid, openid);
        }
        if (StringUtils.hasText(phone)) {
            qw.like(OrderAppointment::getPhone, phone);
        }
        if (status != null) {
            qw.eq(OrderAppointment::getStatus, status);
        }

        Page<OrderAppointment> rs = qw.page(Page.of(page, size));
        rs.getRecords().forEach(this::wrapExtra);
        return rs;
    }

    public Boolean changeStatus(OrderStatusDto dto) {
        String userId = BaseContext.getUserId();
        if(userId == null ){
            userId = BaseContext.getOpenid();
        }
        Assert.isTrue(StringUtils.hasText(userId),"请先登录");

        String id = dto.getId();
        Assert.hasText(id,"ID不能为空");


        return baseMapper.changeStatus(id,dto.getStatus(),dto.getNotes(),userId);
    }
}




